'use strict';

const BaseService = require('./base');
const modelName = 'Task'
function createOrderNumber() {
    // 生成订单号 12位
    return 'T' + new Date().getTime() + Math.floor(Math.random() * 1000);
}
class RouterService extends BaseService {
    constructor(ctx) {
        super(ctx, modelName);
    }
    async create(data) {
        return this.ctx.model[this.modelName].create({
            ...data,
            task_no: createOrderNumber()
        });
    }
    async getPage(where, page, pageSize) {
        return await this.ctx.model[this.modelName].findAndCountAll({
            where,
            offset: pageSize * (page - 1),
            limit: pageSize,
            order: [
                // id 降序
                ['create_time', 'DESC'],
            ],
            include: [
                {
                    model: this.ctx.model.TaskRecord,
                    as: 'children',
                    where: {
                        // status !==0 且 audit_status !-= 0 并且status 不等于 2
                        status: {
                            [this.app.Sequelize.Op.ne]: 0,
                            [this.app.Sequelize.Op.ne]: 2
                        },
                        audit_status: {
                            [this.app.Sequelize.Op.ne]: 0
                        }
                    },
                    // 不影响上一层的数据
                    required: false
                }
            ]
        });
    }
    async findOne(id) {
        return await this.ctx.model[this.modelName].findOne({
            where: {
                id,
            },
            include: [
                {
                    model: this.ctx.model.TaskRecord,
                    as: 'children',
                    where: {
                        status: {
                            [this.app.Sequelize.Op.ne]: 0,
                            [this.app.Sequelize.Op.ne]: 2
                        },
                        audit_status: {
                            [this.app.Sequelize.Op.ne]: 0
                        }
                    },
                    // 不影响上一层的数据
                    required: false
                }
            ]
        });
    }
    async deleteById(id) {
        // 删除所有子任务
        await this.ctx.model.TaskRecord.destroy({
            where: {
                task_id: id
            }
        })
        // 删除钱包中得任务
        await this.ctx.model.Balance.destroy({
            where: {
                task_id: id
            }
        })
        return await this.ctx.model[this.modelName].destroy({
            where: {
                id
            }
        });
    }
}


module.exports = RouterService;
